package com.ityy.ruiji.filter;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.http.HttpRequest;
import com.aliyuncs.http.HttpResponse;
import com.ityy.ruiji.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //这个对象专门用于匹配请求路径与通配符的。   比如： /backend/index.html  可以匹配到/backend/**
    private AntPathMatcher antPathMatcher =new AntPathMatcher();


    /**
     *request与response对象都是tomcat帮你创建的，tomcat帮你创建的对象其实是HttpServletRequest，HttpServletResponse，
     * 只不过现在使用ServletRequest去接收对象而已，ServletRequest与HttpServletREquest的关系是子父类的关系。
     *
     */

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制类型转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //请求url地址
        String uri = request.getRequestURI();

        log.info("拦截到的请求{}",uri);
        //获取白名单
       String[] urls =  new String[]{
               "/employee/login",
               "/employee/logout",
               "/backend/**",
               "/front/**",
               "/user/sendMsg",
               "/user/login"
       };

        //3 检查本次的url是否符合白名单直接放行的路径，如果符合直接放行
       boolean flag = checkUri(uri,urls);

        //4. 如果不符合直接放行路径，那么就应该检查session是有登陆成功标记
        if (flag){
            filterChain.doFilter(request,response);
            return;
        }

        //4-2、判断登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }

        //如果有登陆成功标记可以直接放行
        HttpSession session = request.getSession();
        if (session.getAttribute("employee")!=null){
            filterChain.doFilter(request,response);
            return;
        }

        R result = R.error("NOTLOGIN");
        String jsonString = JSON.toJSONString(result);
        response.getWriter().write(jsonString);
    }

    //匹配本次的请求路径是否与数组中的白名单路径是匹配的。
    private boolean checkUri(String uri,String[] urls) {
        for (String url : urls) {
            //遍历所有的白名单
            if (antPathMatcher.matchStart(url,uri)){
                return true;
            }
        }
        return false;
    }
}
